#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/22 16:52
# @Author  : Samge


def get_where(field_key, field_value, where, op_type='and'):
    """
    拼接sql查询条件
    :param field_key: 字段名
    :param field_value: 字段值
    :param where: 查询语句
    :param op_type: 内层操作类型, 暂时支持 and、or
    :return:
    """
    if not field_value:
        return where
    if type(field_key) is list:
        inner_where = None
        for key in field_key:
            inner_where = get_where(key, field_value, inner_where, op_type=op_type)
        where = f"{where} and" if where else ''
        return f"{where} ({inner_where})"
    else:
        if field_key and (field_value or field_value is 0):
            where = f"{where} {op_type}" if where else ''
            if '%' in field_value:
                symbol = 'not like' if '!%' in field_value else 'like'
                where = f"{where} {field_key} {symbol} '{field_value.replace('!%', '%')}'"
            else:
                symbol = '!=' if '!' in field_value else '='
                where = f"{where} {field_key}{symbol}'{field_value.replace('!', '')}'"
        return where


def sql_value_filter(sql, max_length=20):
    """
    过滤sql操作的传值
    :param sql:
    :param max_length:
    :return:
    """
    dirty_stuff = ["\"", "\\", "/", "*", "'", "=", "-", "#", ";", "<", ">", "+", "%", "$", "(", ")", "%", "@", "!"]
    for stuff in dirty_stuff:
        sql = sql.replace(stuff, "")
    return sql[:max_length]


if __name__ == '__main__':
    username = "1234567890!@#!@#!@#$%======$%"
    username = sql_value_filter(username)  # 防止SQL注入
    print(username)
